package vip.xiaonuo.biz.modular.certification;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import vip.xiaonuo.biz.modular.certification.result.CertificationVO;
import vip.xiaonuo.common.config.ConfigProperties;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.dev.api.DevConfigApi;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CertificationService {

    @Resource
    private DevConfigApi devConfigApi;

    public List<CertificationVO> queryCertificationList(String account) {
        String certification_url = devConfigApi.getValueByKey("CERTIFICATION_URL");
        if (ObjectUtil.isEmpty(certification_url)) throw new CommonException("CERTIFICATION_URL未正确配置");

        List<CertificationVO> resultList = new ArrayList<>();
        String respStr = HttpUtil.get(certification_url + "?userNo=" + account);
        JSONObject jsonObject = JSON.parseObject(respStr);
        if (jsonObject.getIntValue("code") == 200) {
            JSONArray jsonArray = jsonObject.getJSONArray("rows");
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonCer = jsonArray.getJSONObject(i);
                String cerName = jsonCer.getString("certName");
                int state = jsonCer.getIntValue("state");
                Date beginTime = jsonCer.getDate("beginTime");
                Date endTime = jsonCer.getDate("endTime");
                CertificationVO vo = new CertificationVO();
                vo.setCertName(cerName);
                vo.setBeginTime(beginTime);
                vo.setEndTime(endTime);
                vo.setValid(state == 0);
                resultList.add(vo);
            }
        }
        return resultList;
    }
}
